


function factory (ArticleModel) {

  function _getList(res, sortKey, len, filterFn) {
    ArticleModel.find({}, function (err, arts) {
      if (filterFn) {
        arts = arts.filter(filterFn)
      }
      arts.sort(function (o1, o2) {
        return o2[sortKey] - o1[sortKey]
      })
      arts = len === 'all' ? arts : arts.slice(0, len)
      res.send(arts)
    })
  }

  return {
    //  文章_id查找
    id: function (req, res) {
      ArticleModel.findOne({_id: req.query.articleId}, function (err, art) {
        ArticleModel.find({autor: art.autor}, function (err, arts) {
          var elseArts = arts.filter(function (item) {
            return item._id !== art._id
          })
          res.send({currArt: art, elseArticles: elseArts || [] })
        })
      })
    },
    //  文章作者查找
    autor: function (req, res) {
       _getList(res,'time','all' , function (item) {
        return item.autor == req.query.autor
      })
    },
    //  分页
    page: function (req, res) {
      _getList(res,'time','all' , function (item, index) {
        return index >= 10 * (req.query.page - 1) && index < req.query.page * 10
      })
    },
    //  选出精品文章按时间排序
    better: function (req, res){
       _getList(res,'time', 'all', function (item, index) {
        return +item.better
      })
    },
    //  选出最新的5篇文章
    time: function (req, res) {
      _getList(res,'time', 5)
    },
    //  点赞数排序取前5
    good: function (req, res) {
      _getList(res,'good', 5)
    },
    //  获取文章数目
    number: function (req, res) {
      ArticleModel.find({}, function(err, arts) {
        res.send(arts.length)
      })
    }
  }

}

module.exports = factory